package com.ysjy.course.controller;

import com.github.pagehelper.PageInfo;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.UserDto;
import com.ysjy.course.model.YsOrder;
import com.ysjy.course.service.CourseService;
import com.ysjy.course.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(description = "小程序订单管理")
@RequestMapping("/order/user")
@Slf4j
public class OrderController extends BaseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "学生订单列表")
    @RequestMapping(value = "getOrderListByStudent", method = RequestMethod.GET)
    public ResultDTO<PageInfo<YsOrder>> getOrderListByStudent(
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
            @ApiParam(value = "状态:0未支付、1已支付、2退款", required = false) @RequestParam(name = "status", required = false) Integer status,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize
            ) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            params.put("status", status);
            PageInfo<YsOrder> list = orderService.getOrderListByStudent(params,pageNo,pageSize);
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }


    //    {"orderType":1,"goodNumber":"2022052011076175","openId":"o4gSG4vLZ3_GqOQaVyEicxoWFZ6k","studentId":3}
    @ApiOperation(value = "下单",notes = "{\"orderType\":1,\"goodNumber\":\"2022052011076175\",\"openId\":\"o4gSG4vLZ3_GqOQaVyEicxoWFZ6k\",\"studentId\":3}")
    @RequestMapping(value = "putOrder", method = RequestMethod.POST)
    public ResultDTO<YsOrder> putOrder( @Valid @RequestBody YsOrder data){
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (data.getOrderType() == null || data.getGoodNumber() == null || data.getOpenId() == null || data.getStudentId() == null){
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            data.setUserId(userDto.getId());
            data.setMobile(userDto.getMobile());
            if (data.getOpenId() == null) data.setOpenId(userDto.getOpenId());
            return orderService.putOrder(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "订单详情")
    @RequestMapping(value = "getOrderByNumber", method = RequestMethod.GET)
    public ResultDTO<YsOrder> getOrderByNumber(
            @ApiParam(value = "订单号", required = true) @RequestParam(name = "orderNumber", required = true) String orderNumber) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            YsOrder data = orderService.getOrderByNumber(orderNumber);
            return ResultDTO.successResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "删除订单")
    @RequestMapping(value = "delOrder", method = RequestMethod.POST)
    public ResultDTO<YsOrder> delOrder(
            @ApiParam(value = "订单号", required = true) @RequestParam(name = "orderNumber", required = true) String orderNumber,
            @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId) {
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtils.isEmpty(studentId)){
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_STU_NOT_EXIST);
            }
            YsOrder data = orderService.getOrderByNumber(orderNumber);
            if (!data.getStudentId().equals(studentId)){
                return ResultDTO.errorResult("该订单不属于当前学生，无法删除");
            }
            orderService.delOrder(orderNumber);
            return new ResultDTO<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取支付信息",notes = "{\"orderNumber\":\"2022052411111726\",\"openId\":\"o4gSG4vLZ3_GqOQaVyEicxoWFZ6k\"}")
    @RequestMapping(value = "getPayInfo",method = RequestMethod.POST)
    public ResultDTO<String> getPayInfo( @Valid @RequestBody YsOrder data){
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (data.getOrderNumber() == null || data.getOpenId() == null){
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            data.setUserId(userDto.getId());
            return orderService.getPayInfo(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
    }

    @ApiOperation("微信小程序支付回调")
    @RequestMapping(value = "wxPayCallback",method = RequestMethod.POST)
    @ApiImplicitParams({})
    @ResponseBody
    public String wxPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("微信回调 支付号：" + request.getParameter("return_code"));
        InputStream is;
        String inputLine = "";
        String notityXml = "";

        while((inputLine = request.getReader().readLine()) != null){
            notityXml += inputLine;
        }
        //关闭流
        request.getReader().close();
        System.out.println("微信回调内容信息："+notityXml);
        boolean flag = orderService.wxPayCallback(notityXml);
        if (flag){
            return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }else{
            System.out.println("微信验证失败！");
        }
        return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }

    //    {"orderType":1,"goodNumber":"2022052011076175","openId":"o4gSG4vLZ3_GqOQaVyEicxoWFZ6k","studentId":3}
    @ApiOperation(value = "订单申请退款",notes = "{\"orderNumber\":\"2022052411111726\",\"refundWhy\":\"不想上了\",\"refundAmount\":1,\"refundExplain\":\"不想上了，退款说明\"}")
    @RequestMapping(value = "applyRefund", method = RequestMethod.POST)
    public ResultDTO<Boolean> applyRefund(
            @Valid @RequestBody YsOrder data){
        try {
            UserDto userDto = getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (data.getRefundAmount() == null || data.getRefundWhy() == null){
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            data.setUserId(userDto.getId());
            return orderService.applyRefund(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
    }


}